package com.hgd.security.evp.auth.provider;

import com.hgd.security.evp.auth.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author By 尚
 * @date 2019/3/30 17:45
 */
@Component
public class HgdDaoAuthenticationProvider extends DaoAuthenticationProvider {

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;



    public HgdDaoAuthenticationProvider() {
    }

    @PostConstruct
    public void initUserService(){
        this.setUserDetailsService(userService);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        String presentedPassword = authentication.getCredentials().toString();

        boolean matches = passwordEncoder.matches(presentedPassword, userDetails.getPassword());
        if(!matches){
            throw new BadCredentialsException("密码错误");
        }
        super.additionalAuthenticationChecks(userDetails, authentication);
    }
}
